import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by sheep on 2016/1/27.
 */
public class E22_BusyWait {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        //exec.execute(new BusyThread());

        Runnable r1 = new WaitThread();
        Runnable r2 = new SleepTask2(r1);
        exec.execute(r1);
        exec.execute(r2);
        TimeUnit.SECONDS.sleep(5);
        exec.shutdown();
    }
}

class SleepTask implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("休眠3秒");
            TimeUnit.SECONDS.sleep(3);
            Flag.flag = true;

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class SleepTask2 implements Runnable {
    Flag flag = new Flag();

    Runnable otherTask;

    public SleepTask2(Runnable r) {
        otherTask = r;
    }

    @Override
    public void run() {
        try {
            System.out.println("休眠3秒");
            TimeUnit.SECONDS.sleep(3);
            Flag.flag = true;
            synchronized (otherTask){
                otherTask.notifyAll();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("退出run");
    }
}

class BusyThread implements Runnable {
    int count = 0;

    @Override
    public void run() {
        while (!Flag.flag && !Thread.interrupted()) {
            //System.out.println("while");
            count++;
        }
        System.out.println("一共跑了：" + count);
    }
}

class WaitThread implements Runnable {
    int count = 0;
    Flag flag = new Flag();

    @Override
    public void run() {

        while (!Flag.flag && !Thread.interrupted()) {
            count++;
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("一共跑了：" + count);
    }
}

class Flag {
    public static volatile boolean flag = false;
}


